#!/usr/bin/python
# -*- coding:utf-8 -*-

import arrow
import redis
from pymongo import MongoClient

from conf.settings import (
    CLOUD_QUEUE_COUNT,
    CLOUDMONITOR_MONGODB,
    WASS_DB,
    JOB_QUEUE_REDIS,
    JOB_QUEUE_COUNT,
    REDIS_TASK_QUEUE
)
from utility.wx_notify import notify
from utility.log import Logger

wass = MongoClient(CLOUDMONITOR_MONGODB)[WASS_DB]
logger = Logger(filename='monitor_job_queue.log').get_logger()
redis_client = redis.Redis(**JOB_QUEUE_REDIS)
notify_message = []


def monitor_task_count(key):
    """监测redis中任务数量"""
    return redis_client.llen(key)


def main():
    for queue_key in REDIS_TASK_QUEUE:
        task_count = monitor_task_count(queue_key)
        limit = CLOUD_QUEUE_COUNT if 'cloud' in queue_key else JOB_QUEUE_COUNT
        if task_count > limit:
            notify_message.append(f"redis中{queue_key}有{task_count}条任务堆积。")
            logger.info(notify_message[-1])

    trigger_type_map = {'schedule': '周期', 'manual': '单次'}
    for trigger_type, name in trigger_type_map.items():
        query = {
            'addition.triggerType': trigger_type,
            'last_started_at': {'$gt': arrow.utcnow().shift(minutes=-5).datetime},
            'addition.taskType': {'$nin': ['http', 'ping']}
        }
        started = wass.scan_tasks.count_documents(query)
        query.update({'last_started_at': {
            '$gt': arrow.utcnow().shift(minutes=-10).datetime,
            '$lt': arrow.utcnow().shift(minutes=-5).datetime
        }})
        last_5_started = wass.scan_tasks.count_documents(query)
        if notify_message or started > 250:
            notify_message.append(f'最近5分钟开始{name}任务数:{started}, 上5分钟开始{name}任务数:{last_5_started}')
            logger.info(notify_message[-1])


if __name__ == "__main__":
    main()
    notify('\n'.join(notify_message))
